//
//  UserAccount.swift
//  8.31-WH微博
//
//  Created by 吴涵 on 15/9/8.
//  Copyright © 2015年 wuhan. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    ///接口处获取access_token
    
    var access_token: String?
    ///token的 生命周期
    var expires_in: NSTimeInterval = 0{
        didSet{
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    /// 过期日期
    var expiresDate: NSDate?
/// 当前授权用户的UID
    var uid: String?
    //显示用户的名称
    var name: String?
    //用户的头像地址（大图）
    var avatar_large: String?
    
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override var description: String{
    let keys = ["access_token","expires_in","uid","name","avatar_large","expiresDate"]
        return dictionaryWithValuesForKeys(keys).description
    }
    static let accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    func saveUserAccount(){
        printLog("保存路径" + UserAccount.accountPath)
    
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    class func loadUserAccount() -> UserAccount? {
        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccount.accountPath) as? UserAccount
        
        if let date = account?.expiresDate{
            if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            return account
            }
        }
        return nil
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
         name = aDecoder.decodeObjectForKey("name") as? String
    }
}
